package com.example.mymusic;

import static com.example.mymusic.utils.BluetoothController.PERMISSIONS;
import static com.example.mymusic.utils.BluetoothController.REQUEST_CODE;
import static com.example.mymusic.utils.BluetoothController.closeBluetooth;
import static com.example.mymusic.utils.BluetoothController.openBluetooth;
import static com.example.mymusic.utils.Music.currentPosition;
import static com.example.mymusic.utils.Music.isShuffle;
import static com.example.mymusic.utils.Music.mediaPlayer;
import static com.example.mymusic.utils.Music.playMusic;
import static com.example.mymusic.utils.Music.setShuffle;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.mymusic.app.China_MBReceiver;
import com.example.mymusic.app.MyApp;
import com.example.mymusic.app.MyBluetoothConnStateReceiver;
import com.example.mymusic.utils.Comm;
import com.example.mymusic.utils.Music;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private ListView musicListView;
    Switch bluetoothSwitch;//蓝牙开关
    SeekBar seekBar;//歌曲滚动条
    Button button;//播放暂停键
    ArrayAdapter<String> adapter;

    private Boolean isSeeking = false;//是否在拖动进度条

    public MyBluetoothConnStateReceiver mediaButtonReceiver;


    private AudioManager audioManager;
    private AudioFocusRequest audioFocusRequest;
    private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);

        //注册广播,检测蓝牙状态，关闭蓝牙暂停音乐
        mediaButtonReceiver = new MyBluetoothConnStateReceiver();
        IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        registerReceiver(mediaButtonReceiver, intentFilter);


        //监听按钮广播，上面的方式注册不行。
        //AudioManager(音频管理器)注册一个MediaButton对象
        AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        //只有China_MBReceiver能够接收到了，它是出于栈顶的。
        ComponentName chinaCN = new ComponentName(getPackageName(), China_MBReceiver.class.getName());
        mAudioManager.registerMediaButtonEventReceiver(chinaCN);


        musicListView = findViewById(R.id.musicList);
        bluetoothSwitch = findViewById(R.id.bluetoothSwitch);
        seekBar = findViewById(R.id.seekBar);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            seekBar.setMin(0);
        }

        // 扫描本地音乐文件
        requestPermission();
        IncomingCall();

        // 将扫描到的音乐文件显示在ListView中
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Music.nameList) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                if (position == currentPosition) {
                    view.setBackgroundColor(getResources().getColor(R.color.selectedItemColor));
                } else {
                    view.setBackgroundColor(Color.TRANSPARENT);
                }
                return view;

            }
        };
        musicListView.setAdapter(adapter);

        //歌曲列表选中歌曲标红
        musicListView.setOnItemClickListener((adapterView, view, position, l) -> {
            if (currentPosition != position) {
                // 更新选中状态
                currentPosition = position;
                // 通知适配器数据发生了变化
                listViewRefresh();
                playMusic();//切歌
                button.setText("暂停");
            }
        });

        Music.init();
        currentPosition = new Random().nextInt(Music.pathList.size());
        playMusic();
        onMessage(2);

        button = findViewById(R.id.button);

        //点击播放键
        button.setOnClickListener(view -> {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                button.setText("播放");
            } else {
                mediaPlayer.start();
                button.setText("暂停");
            }
        });

        //上一首
        findViewById(R.id.btn_Previous).setOnClickListener((v) -> {
            Music.playPrevious();
        });

        //下一首
        findViewById(R.id.btn_Next).setOnClickListener((v) -> {
            Music.playNext();
        });

        //拖动进度条调转歌曲
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeeking = true;
                Log.d("TAG", "onStartTrackingTouch: " + seekBar.getProgress());
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Log.d("TAG", "onStopTrackingTouch: " + seekBar.getProgress());
                mediaPlayer.seekTo(seekBar.getProgress());
                isSeeking = false;
            }
        });


        bluetoothSwitch.setChecked(openBluetooth(this));

        bluetoothSwitch.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                if (!openBluetooth(this)) bluetoothSwitch.setChecked(false);
            } else {
                if (!closeBluetooth(this)) bluetoothSwitch.setChecked(true);
            }
        });

        //循环加载进度条
        MyApp.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                if (mediaPlayer.isPlaying() && !isSeeking) {
                    seekBar.setProgress(mediaPlayer.getCurrentPosition());
//                    Log.d("TAG", "onCreate: " + seekBar.getProgress());
                }
                MyApp.getMainHandler().postDelayed(this, 1000);
            }
        });

        TextView tv = findViewById(R.id.tv_Shuffle);

        switch (isShuffle) {
            case 0:
                tv.setText("单曲");
                break;
            case 1:
                tv.setText("列表");
                break;
            case 2:
                tv.setText("随机");
                break;
        }

        tv.setOnClickListener(view -> {
            String text = (String) tv.getText();
            if (text.equals("单曲")) {
                tv.setText("列表");
                setShuffle(1);
            } else if (text.equals("列表")) {
                tv.setText("随机");
                setShuffle(2);
            } else {
                tv.setText("单曲");
                setShuffle(0);
            }
        });

        //关闭 蓝牙并且关闭APP
        findViewById(R.id.btn_close).setOnClickListener((v) -> {
            if (closeBluetooth(this)) {
//                ActivityManager am = (ActivityManager)getSystemService (Context.ACTIVITY_SERVICE);
//                Log.d("TAG", "getPackageName: "+getPackageName());
//                am.killBackgroundProcesses(getPackageName());
                System.exit(0);


            }
        });


        //注册监听音频焦点
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        //监听音频焦点,当音频焦点改变时，会回调onAudioFocusChange方法。
        audioFocusChangeListener = focusChange -> {
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_GAIN:
                    // 重新获得音频焦点，恢复播放
                    Music.start();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS:
                    // 长时间失去音频焦点，停止播放并释放资源
                    Music.pause();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    // 暂时失去音频焦点，暂停播放
                    Music.pause();
                    break;
            }
        };

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build();
            audioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
                    .setAudioAttributes(audioAttributes)
                    .setAcceptsDelayedFocusGain(true)
                    .setOnAudioFocusChangeListener(audioFocusChangeListener)
                    .build();
            audioManager.requestAudioFocus(audioFocusRequest);
        } else {
            audioManager.requestAudioFocus(audioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        }

    }



    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)//接收的事件在主线程处理
    public void onMessage(Integer flag) {
        Log.d("TAG", "onMessage: " + flag);
        if (flag == 1) {//滚动条
            setSeekBar();
        } else if (flag == 2) {//歌曲列表
            listViewRefresh();
        } else if (flag == 3) {
            button.setText("暂停");
        } else if (flag == 4) {
            button.setText("播放");
        }
    }

    //切换歌曲重置滚动条
    public void setSeekBar() {
        seekBar.setMax(mediaPlayer.getDuration());
        seekBar.setProgress(0);
    }

    //歌曲列表刷新
    public void listViewRefresh() {
        adapter.notifyDataSetChanged();
        musicListView.setSelection(currentPosition);
    }


    //<editor-fold desc="蓝牙与权限相关内容">

    private static final int PERMISSION_REQUEST_CODE = 1001;

    // 检查是否具有读取外部存储权限
    public boolean checkStoragePermission() {
        int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
        return result == PackageManager.PERMISSION_GRANTED;
    }

    // 请求读取外部存储权限
    private void requestStoragePermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
    }

    private void requestPermission() {
        if (!checkStoragePermission()) {
            requestStoragePermission();
        } else {
            // 已经有权限，可以开始获取音乐文件
            Music.getMusicFiles();
        }
    }

    //请求权限，返回结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (PERMISSION_REQUEST_CODE == requestCode && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 用户授予了权限，可以开始获取音乐文件
            Music.getMusicFiles();
        } else {
            // 如果用户拒绝了权限，可以显示一些提示信息或采取其他措施
        }

        switch (requestCode) {
            //权限的申请结果返回
            case REQUEST_CODE: {
                boolean isAllPermissionPass = true;
                for (String permission : PERMISSIONS) {
                    if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                        isAllPermissionPass = false;
                        break;
                    }
                }
                if (isAllPermissionPass) {
                    Toast.makeText(this, "授权成功！", Toast.LENGTH_SHORT).show();
                    openBluetooth(this);
                } else {
                    finish();
                }
            }
        }
    }

    //电话权限
    private void IncomingCall() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_CALL_LOG}, REQUEST_CODE);
        }
    }

    //</editor-fold>


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 在Activity销毁时释放MediaPlayer资源
        Music.release();


        Comm.put(Comm.FlagKey, 0);

        EventBus.getDefault().unregister(this);

        unregisterReceiver(mediaButtonReceiver);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && audioFocusRequest != null) {
            audioManager.abandonAudioFocusRequest(audioFocusRequest);
        } else {
            audioManager.abandonAudioFocus(audioFocusChangeListener);
        }
    }
}